package com.lagou.client;

import com.lagou.protocol.RpcRequest;
import com.lagou.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class ClientResponseHandler extends ChannelInboundHandlerAdapter {

    private ConcurrentHashMap<String, RpcResponse> resultMap;

    public ClientResponseHandler(ConcurrentHashMap<String, RpcResponse> resultMap) {
        this.resultMap = resultMap;
    }

    /**
     * 收到服务端数据
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        RpcResponse response = (RpcResponse) msg;
        String threadInfo = response.getThreadInfo();
        if (resultMap.containsKey(threadInfo)) {
            RpcResponse rpcResponse = resultMap.get(threadInfo);
            rpcResponse.setResult(response.getResult());
            rpcResponse.getLatch().countDown();
        } else {
            System.out.println("wrong threadInfo: " + threadInfo);
        }
    }
}
